import AsyncStorage from "@react-native-community/async-storage";
import { HOST, WS } from "../config/dev";
import { CURRENT_USER_KEY } from "../storage";
import {UPDATE_MESSAGE_LIST} from "../store/reducer/message";
import { MESSAGE_TYPE } from "../types/message";
import Store from '../store'

class Chat{
    static getInstance() {
        if(!this.instance) {
            this.instance = new Chat()
        }
        return this.instance
    }

   async setUp() {
       const userStr = await AsyncStorage.getItem(CURRENT_USER_KEY)
       const user = userStr ? JSON.parse(userStr) : null;
       if (!user) {
        return { status: false, errmsg: '登陆已失效' };
      }
    this.userInfo = user;

    this.chatSocket = new WebSocket(WS+'push/'+user.userId+'/');
    this.chatSocket.onopen = e=> {
        console.log(e, 'open')
    }
    this.chatSocket.onmessage = e=> {
       const data = JSON.parse(e.data)
       this.reciveMessage(data)
    //    if (!data.isGroup){
    //     this.reciveMessage(data.event)
    //    }
    //    if(data.type=== MESSAGE_TYPE.CONFIRM){

    //        this.confirmMessage(data.event)
    //    }
    }

    this.chatSocket.onclose = e=> {
        console.log(e, 'close')
    }
    this.chatSocket.onerror = e => {
        console.log(e, 'error')
    }
    return { status: true, errmsg: '登陆已失效' };
  }
//  发送消息
  sendMessage (data) {
        this.chatSocket.send(JSON.stringify({data}))
        Store.dispatch({
            type: UPDATE_MESSAGE_LIST,
            payload: {list: [{...message}], isRead: true, currentUserId: this.userInfo.userId }
          })
        return {status: true}
  }
  // 接受好友的消息
  reciveMessage (data) {
    const message = data.event
    if(message) {
        Store.dispatch(
            {
                type: UPDATE_MESSAGE_LIST, 
                payload:{list: [message], currentUserId: this.userInfo.userId}
            }
            )
    }
  }
  confirmMessage(data) {
      console.log('确认收到信息')
  }
}

export default Chat.getInstance()